package com.csht.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

import net.sf.json.JSONObject;

/**
 * 获取短信验证码类
 * 
 * @author Administrator
 *
 */
public class GetMessage {

	/**
	 * 用户ID
	 */
	public static final String ACCOUNT_SID = "bf28336da50c48a69a4814eaeb86d69a";// 这里填写你在平台里的ACOUNT_SID

	/**
	 * 密钥
	 */
	public static final String AUTH_TOKEN = "ec642528b07a427daf5ff3f9a7c972e6";

	/**
	 * 请求地址前半部分
	 */
	public static final String BASE_URL = "https://api.miaodiyun.com/20150822/industrySMS/sendSMS";// 请求地址是固定的不用改

	public static String randNum = RandUtil.getRandNum(); //获取6位随机验证码

	public static String smsContent = "";

	/**
	 * (获取短信验证码)
	 * 
	 * @param to
	 * @return String
	 */
	public static String getResult(String to, String getCodeType) {
		randNum = RandUtil.getRandNum(); //获取6位随机验证码
		if("register".equals(getCodeType)) {
			smsContent = "【校园闲置商品交易平台】尊敬的用户，您好，您正在注册校园闲置商品交易平台网站，验证码为：" + randNum + "，若非本人操作请忽略此短信。";
		}else if("findUsername".equals(getCodeType)) {
			smsContent = "【校园闲置商品交易平台】尊敬的用户，您好，您正在申请找回用户名，验证码为：" + randNum + "，若非本人操作请忽略此短信。";
		}else if("findPassword".equals(getCodeType)) {
			smsContent = "【校园闲置商品交易平台】尊敬的用户，您好，您正在申请修改密码，验证码为：" + randNum + "，若非本人操作请忽略此短信。";
		}else if(getCodeType.contains("已被预订")){ //卖家('已被预订'是判断是卖家信息内容还是买家的信息内容)
			smsContent = "你的验证码为：" + getCodeType;
		}else { //买家
			smsContent = "验证码为：" + getCodeType;
		}
		
		String args = QueryUtil.queryArguments(ACCOUNT_SID, AUTH_TOKEN, smsContent, to);
		OutputStreamWriter out = null;
		InputStream in = null;
		BufferedReader br = null;
		StringBuffer sb = new StringBuffer();

		try {
			URL url = new URL(BASE_URL);
			URLConnection connection = url.openConnection(); // 打开链接
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setConnectTimeout(5000); // 设置链接超时
			connection.setReadTimeout(10000); // 设置读取超时

			// 提交数据
			out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
			out.write(args);
			out.flush();

			// 读取返回数据
			br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line = "";
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null) {
					br.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		JSONObject jsonObject = JSONObject.fromObject(sb.toString());
		System.out.println(jsonObject);
		Object object = jsonObject.get("respCode");
		System.out.println("状态码：" + object + "验证码：" + randNum);
		System.out.println(!object.equals("00000"));
		if (!object.equals("00000")) {
			return object.toString();
		} else {

			return randNum;
		}

	}
}
